<?php

use yii\grid\GridView;
use yii\helpers\Html;

/* @var $this yii\web\View */
/* @var $searchModel app\models\search\ArcProgressSearchModel */
/* @var $dataProvider yii\data\ActiveDataProvider */

$this->title = 'CTI文件已分类';
$this->params['breadcrumbs'][] = $this->title;
?>
<!-- 时间范围选择器 -->
<link rel="stylesheet" href="<?= $url_base?>/assets/public/bootstrap-daterangepicker/daterangepicker.css"/>
<div class="arc-progress-index">
    <!-- 	查询开始与结束的日期 -->
    <div class="form-group">
        <label>选择"训练时间"时间的范围进行筛选:</label>
        <div class="input-group">
            <div class="input-group-addon">
                <i class="fa fa-clock-o"></i>
            </div>
            <input class="form-control pull-right" id="reservationtime" readonly="readonly">
        </div>
    </div>
    <div class="form-group">
        <form action="index" id="callTimeClass" target="blank">
            <a class='btn btn-info fa fa-search' type='button'  id = 'getTime'>根据训练时间筛选</a>
        </form>
    </div>

    <?php // echo $this->render('_search', ['model' => $searchModel]); ?>
    <p>
        <?= Html::a('刷新本页', [""], ['class' => 'btn btn-success fa fa-refresh']) ?>
    </p>
    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'showFooter' => true,  //设置显示最下面的footer
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],
            ['attribute' => 'id',
                'footer' => '
                    <input id="num"  type="number" href="#" class="btn btn-default btn-xs btn-delete" placeholder="每页显示的条数"/>
                ',
            ],
            ['attribute' => 'arc_train',
                //通过这种方法滤掉更方便
                'filter' => Html::activeDropDownList($searchModel,
                    'arc_classify', \yii\helpers\ArrayHelper::map((new \app\models\ArcClassify())->find()->all(), 'id', 'name'),
                    ['prompt' => '全部', 'class' => 'form-control']),
                'value' =>
                    function($model){
                        if (!empty($model)){
                            $arc_classify = $model->arc_classify;
                            return \app\models\ArcClassify::findOne($arc_classify)->name.'';
                        }else{
                            return "";
                        }
                    },
                'label'=>'训练模型',
                'format' => 'raw',//表示显示的是html格式的
                'options'=>[
                    'width'=>'13%',
                ]
            ],
            ['attribute' => 'thing_recordfile',
                'value' =>
                    function($model){
                        if (!empty($model)){
                            $Filepath = \app\models\ThingRecordFile::findOne($model->thing_recordfile)->Filepath;
                            $filePath = \common\helps\Tools::getFilePath($Filepath);
                            if(strlen($filePath)>20){
                                $tempStr = mb_substr($filePath, 0,20).'...';   //主要通过此种方式实现
                                return '<div title="'.$filePath.'">'.$tempStr.'</div>';
                            }else{
                                return $filePath.'';
                            }
                        }else{
                            return "";
                        }
                    },
                'label'=>'文件路径',
                'format' => 'raw',//表示显示的是html格式的
                'options'=>[
                    'width'=>'10%',
                ]
            ],
            ['attribute' => 'create_time',
                'value' =>
                    function($model){
                        if (!empty($model)){
                            return date("Y年m月d日 H:i:s",$model->create_time);
                        }else{
                            return "";
                        }
                    },
                'label'=>'训练时间',
                'format' => 'raw',//表示显示的是html格式的
                'options'=>[
                    'width'=>'14%',
                ]
            ],
            ['attribute' => 'progress',
                'filter' => Html::activeDropDownList($searchModel,
                    'progress', [0=>"未训练",1=>"正在训练",2=>"训练完成",4=>"文件被删除"],
                    ['prompt' => '全部', 'class' => 'form-control']),
                'value' =>
                    function($model){
                        try {
                            $progress = $model->progress;
                            if ($progress == 0){
                                return '<div style="color:#f39c12">未训练</div>';
                            }elseif ($progress == 1) {
                                return '<div style="color:#00c0ef">正在训练</div>';
                            }elseif($progress == 2) {
                                return '<div style="color:#00a65a">训练完成</div>';
                            }elseif($progress == 4) {
                                return '<div style="color:red">文件被删除</div>';
                            }
                        }catch (\Exception $e){
                            return '<div style="color:#dd4b39">无状态</div>';
                        }
                    },
                'label'=>'训练状态',
                'format' => 'raw',//表示显示的是html格式的
                'options'=>[
                    'width'=>'10%',
                ]
            ],
            ['attribute' => 'user',
                'value' =>
                    function($model){
                        try{

                            if (!empty($model)){
                                $user = \common\models\User::findOne(\app\models\ArcTrain::findOne($model->arc_train)->user);
                                $username = "";
                                if(!empty($user)){
                                    $username = $user->username;
                                    return $username."";
                                }else{
                                    return $username."";
                                }
                            }else{
                                return "";
                            }
                        }catch(\Exception $exception){
                            return "";
                        }
                    },
                'label'=>'训练用户',
                'format' => 'raw',//表示显示的是html格式的
                'options'=>[
                    'width'=>'8%',
                ]
            ],
            ['attribute' => 'ip',
                'value' =>
                    function($model){
                        try{
                            if (!empty($model)){
                                $ip = \app\models\ArcTrain::findOne($model->arc_train)->ip;
                                return $ip.'';
                            }else{
                                return "";
                            }
                        }catch(\Exception $exception){
                            return "";
                        }
                    },
                'label'=>'训练IP',
                'format' => 'raw',//表示显示的是html格式的
                'options'=>[
                    'width'=>'13%',
                ]
            ],
            ['attribute' => 'arc_classify_status',
                'filter' => Html::activeDropDownList($searchModel,
                    'arc_classify_status', [1=>"有情绪",2=>"无情绪"],
                    ['prompt' => '全部', 'class' => 'form-control']),
                'value' =>
                    function($model){
                        try {
                            $arc_classify_status = $model->arc_classify_status;
                            if ($arc_classify_status == 2){
                                return '<div style="color:green">无情绪</div>';
                            }elseif ($arc_classify_status == 1) {
                                return '<div style="color:red">有情绪</div>';
                            }else{
                                return '<div style="color:#dd4b39">无状态</div>';
                            }
                        }catch (\Exception $e){
                            return '<div style="color:#dd4b39">无状态</div>';
                        }
                    },
                'label'=>'情绪有无',
                'format' => 'raw',//表示显示的是html格式的
                'options'=>[
                    'width'=>'8%',
                ]
            ],
            ['attribute' => 'arc_language',
             'filter' => '<input type="text" class="form-control" placeholder="输入查询" name="ArcProgressSearchModel[arc_language]">',
                'value' =>
                    function ($model,$url,$key){
                        try {
                            $arc_classify = \app\models\ArcClassify::findOne($model->arc_classify);
                            $arc_problems_arr = explode('|', $arc_classify->content);
                            $arc_language = $model->arc_language;
                            $result = \common\helps\Tools::recogniseBaiduToHtml($arc_problems_arr,$arc_language);
                            $formatterResult = \common\helps\Tools::recogniseBaiduToHtmlFormatter($result);
                            $results = "";
                            foreach ($result as $k=>$v){
                                $results = $results.$v[0]."。\r\n";
                            }
                            //将结果格式化，有。号就换行
                            $var = '<div class="btn-group" id="hover'.$key.'" style="max-height: 40px;overflow: auto" title="'.htmlspecialchars($results).'">
                                                    <a href="#" >'."点击查看识别结果".'
                                                    </a>
                                              <div class="dropdown-menu " style="padding:10px;max-height: 300px;max-width: 300px;overflow: auto" role="menu">
                                              </div>
                                            </div>';
                            $hidden = '<div hidden="hidden" id="formatterResult'.$key.'">'.$formatterResult.'</div>';
                            $script = "
                                <script>
                                    $('#hover$key').click(function() {
                                      $('#asrRes').removeAttr('hidden');
                                      $('#chatId').html($('#formatterResult$key').html());
                                    });
                                </script>
                                ";
                            return $var.$hidden.$script;
                        }catch (\Exception $e){
                            return '<div style="color:red">无识别结果</div>';
                        }
                    },
                'label'=>'识别结果',
                'format' => 'raw',//表示显示的是html格式的
                'options'=>[
                    'width'=>'12%',
                ]
            ],
            ['class' => 'yii\grid\ActionColumn',//下面是新增加的按按钮
                'header' => '操作',
                'template' => '{view}  {play} ',
                'buttons' => [
                    'view'=> function ($url, $model, $key) {
                        $url = 'view?id='.$key.'&page='.(isset($_GET['page'])?$_GET['page']:0).'&per-page='.(isset($_GET['per-page'])?$_GET['per-page']:0);
                        $result = Html::a('<span class="btn btn-success fa fa-sticky-note-o">详情</span>&nbsp;', $url,
                            ['id' => 'view',
                                'title' => '查看详细信息'] );
                        return $result;
                    },
                    'play' => function ($url, $model, $key) {
                        $model = \app\models\ThingRecordFile::findOne($model->thing_recordfile);
                        $Filepath = $model->Filepath;
                        $progress = $model->getArcProgress()->one();
                        $filepath = \common\helps\Tools::getFilePath($Filepath);
                        if(!empty($progress) ){
                            if($progress->progress == 4){
                                $resStr = '<a id="modal_'.$key.'"
                                    class="btn btn-danger fa fa-danger"
                                    href="#"
                                    title="该文件不存在，需要到CTI中重新上传">无文件</a>&nbsp;';
                            }else{
                                $resStr = '<a id="modal_'.$key.'"
                                    class="btn btn-info fa fa-download"
                                    href="../common/play-download?httpFilePath='.htmlspecialchars($filepath).'"
                                    title="请点击该机器人进行修改以及查看" data-toggle="modal"
                                    data-target="#create-modal">下载</a>&nbsp;';
                            }
                        }else{
                            $resStr = '<a id="modal_'.$key.'"
                                    class="btn btn-info fa fa-download"
                                    href="../common/play-download?httpFilePath='.htmlspecialchars($filepath).'"
                                    title="请点击该机器人进行修改以及查看" data-toggle="modal"
                                    data-target="#create-modal">下载</a>&nbsp;';
                        }
                        return $resStr.'';
                    },
                ],
                'options' => [
                    'width' => '15%',
                ],
            ],
            //'arc_classify',
            //'arc_classify_status',
            //'arc_problems:ntext',

        ],
        'pager'=>[
            'firstPageLabel'=>"第一页",
            'lastPageLabel'=>'最后一页',
        ],
    ]); ?>
</div>
<?= $this->render('/common/dialog')?>
<div id="asrRes" class="box box-warning direct-chat direct-chat-warning" style="width:500px;position:absolute;
top:20px;z-index: 99999;left: 50%;margin-left: -250px;top:50%;margin-top:-200px;" hidden="hidden">
    <div class="box-header with-border">
        <h3 class="box-title">识别结果（点击该页面进行关闭）</h3>
        <div class="box-tools pull-right">
            <button type="button" class="btn btn-box-tool" data-toggle="tooltip" title="" data-widget="chat-pane-toggle" data-original-title="Contacts">
                <i class="fa fa-comments"></i></button>
            </button>
        </div>
    </div>
    <!-- /.box-header -->
    <div class="box-body">
        <!-- Conversations are loaded here -->
        <div class="direct-chat-messages" id="chatId">
            大叔大婶
        </div>
        <!--/.direct-chat-messages-->

    </div>
    <!-- /.box-body -->
</div>
<script type="text/javascript">
    $('#num').blur(function(){//当鼠标失去焦点是触发事件,实现用户自定义分页
        var url = "<?= 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'] ?>";
        $.ajax({
            type:'post',
            async:true,
            url:url,
            data:{pageSize:$('#num').val()},
            success:function(data){
                window.location.reload();
            },
            error:function(error){

            }
        });
    });
    $('#asrRes').click(function(){
        $(this).attr('hidden','hidden');
    });
</script>
<!-- 时间范围选择器 -->
<script src="<?= $url_base ?>/assets/public/moment/min/moment.min.js"></script>
<script src="<?= $url_base ?>/assets/public/bootstrap-daterangepicker/daterangepicker.js"></script>
<script type="text/javascript">
    // 	将选择的时间拿到，将其显示的为中文
    var res = $('#reservationtime').daterangepicker({
            maxDate : moment(), //最大时间
            dateLimit : {
                days : 99999
            }, //起止时间的最大间隔
            showDropdowns : true,
            showWeekNumbers : false, //是否显示第几周
            timePicker : true, //是否显示小时和分钟
            timePickerIncrement : 60, //时间的增量，单位为分钟
            timePicker12Hour : false, //是否使用12小时制来显示时间
            ranges : {
                '最近1小时': [moment().subtract('hours',1), moment()],
                '今日': [moment().startOf('day'), moment()],
                '昨日': [moment().subtract('days', 1).startOf('day'), moment().subtract('days', 1).endOf('day')],
                '最近7日': [moment().subtract('days', 6), moment()],
                '最近30日': [moment().subtract('days', 29), moment()],
                '最近100日': [moment().subtract('days', 99), moment()]
            },
            opens : 'right', //日期选择框的弹出位置
            buttonClasses : [ 'btn btn-default' ],
            applyClass : 'btn-small btn-primary blue',
            cancelClass : 'btn-small',
            separator : ' to ',
            locale : {
                applyLabel : '确定',
                cancelLabel : '取消',
                fromLabel : '起始时间',
                toLabel : '结束时间',
                separator: '   -   ',
                format: 'YYYY年MM月DD日 HH:mm:ss', //控件中from和to 显示的日期格式
                customRangeLabel : '自定义',
                daysOfWeek : [ '日', '一', '二', '三', '四', '五', '六' ],
                monthNames : [ '一月', '二月', '三月', '四月', '五月', '六月',
                    '七月', '八月', '九月', '十月', '十一月', '十二月' ],
                firstDay : 1
            }
        },function(start, end, label) {//格式化日期显示框
            $('#reservationtime').val(start.format('YYYY-MM-DD HH:mm:ss') + ' - ' + end.format('YYYY-MM-DD HH:mm:ss'));
        }
    );
    /*点击下面的会提交日期的区间 */
    $('#getTime').click(function(){
        var url = "index?timeZones="+$("#reservationtime").val();
        window.location.href=url;
    });
</script>
<!-- 	设置日期组建的日期为拿到的get的时间 -->
<?php
if(isset($_GET['timeZones'])){
    $timeZones = $_GET['timeZones'];
    ?>
    <script type="text/javascript">
        $('#reservationtime').val('<?= $timeZones ?>');
    </script>
    <?php
}
?>
